# encoding: utf-8
from django.shortcuts import render_to_response
from django.http.response import (HttpResponse, HttpResponseRedirect,
                                  HttpResponseNotFound, HttpResponseBadRequest,
                                  HttpResponseForbidden)
from lunch.models import User, Record, Food, PaidItem, Recommend
from django.template.context import Context
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import datetime
import requests
import base64
import hashlib
import threading
from django.contrib.auth.decorators import login_required
import calendar
from django.contrib import auth

LAST_HOUR = 10
LAST_HOUR_MIN = 30
SUBSIDY = 8
# Create your views here.


def hashfn(s):
    return base64.b64encode(hashlib.md5(s).hexdigest())


def send_email(host, user):
    login_url = 'http://%s/lunch/login?user=%s&hash=%s' %\
        (host, user, hashfn(user + settings.SECRET_KEY))
    data = {
          "from":
            "Lunch Mailer"\
            "<postmaster@sandbox121db25121d54abb85269d5472b2c3b6.mailgun.org>",
          "to": "Dear %s<%s@useease.com>" % (user, user),
          "subject": "Login Link",
          "text": login_url}
    url = "https://api.mailgun.net/v2/"\
        "sandbox121db25121d54abb85269d5472b2c3b6.mailgun.org/messages"
    rsp = requests.post(
                        url,
                        auth=("api", "key-8cb4ef103ded7d5577a8d0b930add2df"),
                        data=data)
    print rsp.content


def index(request):
    context = Context()
    today = datetime.date.today()
    user = request.session.get('user')
    if user:
        try:
            userobj = User.objects.get(user=user)
            context['today_records'] = (Record.objects.filter(target=today,
                                                              user=userobj))
        except User.DoesNotExist as _unused:
            return HttpResponseNotFound("404 User not found.")

    foods = Food.objects.filter(end__gte=today).filter(begin__lte=today)
    context['foods'] = foods
    d1 = datetime.datetime.now()
    context['orders'] = Record.objects.filter(target=today)
    if user:
        context['recommends'] = Recommend.objects.filter(user=userobj).filter(target=today).order_by('-score')
        context['user'] = userobj
        if userobj.balance <= 5:
            context['balance_notify'] = True
    d3 = datetime.datetime(d1.year, d1.month, d1.day, LAST_HOUR, LAST_HOUR_MIN, 0, 0)
    if d3 > d1:
        context['today'] = True
    else:
        context['today'] = False
    # 管理员无限制
    if request.user.is_authenticated():
        context['today'] = True
    context['collects'] = Record.objects.collect()
    context['sum_money'] = Record.objects.sum_money()
    return render_to_response('lunch/index.html', context)


@csrf_exempt
def login(request):
    if request.method == 'POST':
        user = request.POST.get("user")
        try:
            userobj = User.objects.get(user=user)
        except User.DoesNotExist as _unused:
            userobj = User(user=user, balance=0)
            userobj.save()
        t1 = threading.Thread(target=send_email,
                              args=(request.get_host(), user))
        t1.start()
        return HttpResponse("OK")
    elif request.method == 'GET':
        user = request.GET.get('user')
        if not user:
            return HttpResponseBadRequest("请输入有效姓名全拼")
        hashstr = request.GET.get('hash')
        if hashfn(user + settings.SECRET_KEY) == hashstr:
            request.session['user'] = user
            return HttpResponseRedirect("/lunch/")
        else:
            return HttpResponseForbidden("""
            <script>alert("认证失败");window.location.href="/";</script>
            """)


@csrf_exempt
def order(request):
    user = request.session.get('user')
    if not user:
        return HttpResponseForbidden("您必须登录，在右上方输入您的姓名全拼，点击后进入公司邮箱，通过登录链接登录。")
    userobj = User.objects.get(user=user)
    today = datetime.date.today()
    d1 = datetime.datetime.now()
    d2 = datetime.datetime(d1.year, d1.month, d1.day, LAST_HOUR, LAST_HOUR_MIN, 0, 0)
    if d2 <= d1 and not request.user.is_authenticated():
        return HttpResponseBadRequest("已过点餐时间了")
    itemid = request.POST.get('item')
    if not itemid:
        return HttpResponseBadRequest("非法请求")
    try:
        food = Food.objects.get(id=itemid)
    except Food.DoesNotExist as _unused:
        return HttpResponseBadRequest("今天似乎没有这个菜。")
    if food.begin > today or food.end < today:
        return HttpResponseBadRequest("过期菜系")
    # 先看看今天公司一共为此名员工付了多少
    rs = PaidItem.objects.filter(target=today, user=userobj)
    if not rs:
        epaid = food.price - SUBSIDY if food.price >= SUBSIDY else 0
        cpaid = SUBSIDY if food.price >= SUBSIDY else food.price
        userobj.balance -= epaid
        rsobj = PaidItem(
            user=userobj,
            target=today,
            cpaid=cpaid,
            epaid=epaid
        )
        rsobj.save()
    else:
        rsobj = rs[0]
        if rsobj.cpaid < SUBSIDY:
            if food.price + rsobj.cpaid <= SUBSIDY:
                rsobj.cpaid += food.price
                rsobj.epaid += 0
                userobj.balance -= 0
            else:
                cur_cpaid = SUBSIDY - rsobj.cpaid
                rsobj.cpaid += cur_cpaid
                cur_epaid = food.price - cur_cpaid
                rsobj.epaid += cur_epaid
                userobj.balance -= cur_epaid
        else:
            rsobj.epaid += food.price
            rsobj.cpaid += 0
            userobj.balance -= food.price
        rsobj.save()
    r1 = Record(oprdate=d1,
                target=today,
                user=userobj,
                food=food.name,
		price=food.price)
    r1.save()
    userobj.save()
    return HttpResponse("OK")


def logout(request):
    request.session['user'] = None
    return HttpResponseRedirect("/lunch/")


@csrf_exempt
def abort_today(request):
    d1 = datetime.datetime.now()
    d2 = datetime.datetime(d1.year, d1.month, d1.day, LAST_HOUR, LAST_HOUR_MIN, 0, 0)
    if d2 <= d1:
        return HttpResponseBadRequest("已过点餐时间了")
    user = request.session.get('user')
    if not user:
        return HttpResponseForbidden(u"您必须登录，在右上方输入您的姓名全拼，点击后进入公司邮箱，通过登录链接登录。")
    userobj = User.objects.get(user=user)
    today = datetime.date.today()
    d1 = datetime.datetime.now()
    d2 = datetime.datetime(d1.year, d1.month, d1.day, LAST_HOUR, LAST_HOUR_MIN, 0, 0)
    rs = (Record.objects.filter(user=userobj)
                        .filter(target=today))
    if not rs:
        return HttpResponseBadRequest(u"今天还没有选择菜品，无需取消")
    if d2 <= d1:
        return HttpResponseBadRequest(u"已过点餐时间, 无法退回了，抱歉。")
    r1 = rs[0]
    userobj.balance += r1.epaid
    userobj.save()
    rs.delete()
    return HttpResponse("取消成功")


@login_required(login_url="/lunch/admin_login/")
def instead(request, user):
    login_url = 'http://%s/lunch/login?user=%s&hash=%s' %\
        (request.get_host(), user, hashfn(user + settings.SECRET_KEY))
    url_html = "<a href='%s'>%s</a>" % (login_url, user)
    return HttpResponse(url_html)


@login_required(login_url="/lunch/admin_login/")
def tongji(request):
    return HttpResponseRedirect(datetime.date.today().strftime("%Y%m%d"))


@login_required(login_url="/lunch/admin_login/")
def tongji_day(request, _day):
    day = datetime.datetime.strptime(_day, "%Y%m%d").date()
    context = Context()
    records = PaidItem.objects.filter(target=day)
    # 全为0的就不要显示了。或者在客户端删除也行。
    records = [el for el in records if el.cpaid]
    context['records'] = records
    context['cur_date'] = day
    return render_to_response('lunch/tongji.html', context)


@csrf_exempt
def abort_item(request, itemid):
    d1 = datetime.datetime.now()
    d2 = datetime.datetime(d1.year, d1.month, d1.day, LAST_HOUR, LAST_HOUR_MIN, 0, 0)
    if d2 <= d1:
        return HttpResponseBadRequest("已过点餐时间了")
    user = request.session.get('user')
    if not user:
        return HttpResponseForbidden(u"您必须登录，在右上方输入您的姓名全拼，点击后进入公司邮箱，通过登录链接登录。")
    userobj = User.objects.get(user=user)
    today = datetime.date.today()
    try:
        record = Record.objects.get(user=userobj, target=today, id=itemid)
    except Record.DoesNotExist as _unused:
        return HttpResponseBadRequest("未找到这一项订餐请求")
    rsobj = PaidItem.objects.get(user=userobj, target=today)
    if rsobj.epaid - record.price >= 0:
        rsobj.epaid -= record.price
        userobj.balance += record.price
    else:
        _epaid = rsobj.epaid
        rsobj.epaid = 0
        rsobj.cpaid -= record.price - _epaid
        userobj.balance += _epaid
    rsobj.save()
    userobj.save()
    record.delete()
    return HttpResponse("OK")


@login_required(login_url="/lunch/admin_login/")
def menu_manage(request):
    context = Context()
    foods = Food.objects.all()
    today = datetime.date.today()
    max_day = calendar.monthrange(today.year, today.month)[1]
    first_day = datetime.date(today.year, today.month, 1)
    second_day = datetime.date(today.year, today.month, 10)
    second_day_plus = datetime.date(today.year, today.month, 11)
    third_day = datetime.date(today.year, today.month, 20)
    third_day_plus = datetime.date(today.year, today.month, 21)
    end_day = datetime.date(today.year, today.month, max_day)
    context['whole'] = foods.filter(begin=first_day, end=end_day)
    context['first'] = foods.filter(begin=first_day, end=second_day)
    context['second'] = foods.filter(begin=second_day_plus, end=third_day)
    context['third'] = foods.filter(begin=third_day_plus, end=end_day)
    foods_count = foods.count()
    cycle_num = foods_count / 5
    cycle_num += 1 if foods_count % 5 else 0
    context['foods'] = [foods[5 * i: (i + 1) * 5] for i in range(cycle_num)]
    return render_to_response('lunch/menu.html', context)


@csrf_exempt
def config_menu_item(request, itemid):
    today = datetime.date.today()
    max_day = calendar.monthrange(today.year, today.month)[1]
    first_day = datetime.date(today.year, today.month, 1)
    second_day = datetime.date(today.year, today.month, 10)
    second_day_plus = datetime.date(today.year, today.month, 11)
    third_day = datetime.date(today.year, today.month, 20)
    third_day_plus = datetime.date(today.year, today.month, 21)
    end_day = datetime.date(today.year, today.month, max_day)
    # opr
    target = request.POST.get('target')
    if not target:
        return HttpResponseBadRequest("ERROR")
    try:
        item = Food.objects.get(id=itemid)
    except Food.DoesNotExist as _unused:
        return HttpResponseBadRequest("ERROR NOT FOUND")
    if target == 'first':
        item.begin = first_day
        item.end = second_day
    elif target == 'second':
        item.begin = second_day_plus
        item.end = third_day
    elif target == 'third':
        item.begin = third_day_plus
        item.end = end_day
    elif target == 'whole':
        item.begin = first_day
        item.end = end_day
    else:
        return HttpResponseBadRequest("ERROR SYNTAX")
    item.save()
    return HttpResponse("OK")


@csrf_exempt
def admin_login(request):
    if request.method == 'GET':
        if request.user.is_authenticated():
            next_url = request.GET.get("next")
            if next_url is not None:
                return HttpResponseRedirect(next_url)
            return HttpResponseRedirect("hrefs/")
        return render_to_response('lunch/login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get("password")
        next_url = request.GET.get("next")
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            if next_url is not None:
                return HttpResponseRedirect(next_url)
            return HttpResponseRedirect("hrefs/")
        else:
            return HttpResponseForbidden("登录失败")


@login_required(login_url="/lunch/admin_login/")
def admin_hrefs(request):
    context = Context()
    context['peoples'] = User.objects.all()
    return render_to_response("lunch/hrefs.html", context)


def admin_logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/lunch/admin_login/")


@csrf_exempt
@login_required(login_url="/lunch/admin_login/")
def charge(request, username):
    amount = request.POST.get("amount")
    if not amount:
        return HttpResponseBadRequest("金额有误")
    try:
        amount = float(amount)
    except ValueError as _unused:
        return HttpResponseBadRequest("金额错误")
    users = User.objects.filter(user=username)
    if not users:
        return HttpResponseBadRequest("用户有误")
    user = users[0]
    user.balance += amount
    user.save()
    return HttpResponse("充值成功。")


@csrf_exempt
@login_required(login_url="/lunch/admin_login/")
def food_add(request):
    today = datetime.date.today()
    name = request.POST.get("foodname")
    price = request.POST.get("foodprice")
    if not name:
        return HttpResponseBadRequest("菜品名为空，添加失败")
    if not price:
        return HttpResponseBadRequest("菜品价格为空，添加失败")
    foods = Food.objects.filter(name=name)
    if foods:
        return HttpResponseBadRequest("菜品已存在")
    food = Food(name=name, begin=today, end=today, price=price)
    food.save()
    return HttpResponse("添加成功")

# TODO: 猜你喜欢 TOP10
# TODO: 一周计划，隔日点餐
# TODO: 历史热门
